<template>
	<view class="container">
		<view class="tabs">
			<view 
				v-for="(tab, index) in tabs" 
				:key="index"
				:class="['tab-item', {active: currentTab === index}]"
				@click="switchTab(index)"
			>
				{{tab.name}}
			</view>
		</view>
		<view v-if="!Object.keys(foodsOrders).length" class="d-flex w-100 h-100 flex-column just-content-center align-items-center">
			<!-- <ourLoading active background-color="" color="#289365" text=" " /> -->
			<view class="tips d-flex flex-column align-items-center font-size-base text-color-assist">
				<view>您还没有下单</view>
				<view>快去犒劳一下自己吧~</view>
			</view>
			<button type="primary" class="drink-btn" style="z-index: 3001;" size="default" @tap="menu">去订餐</button>
		</view>
		<template v-else>
			<view class="order-box" v-for="(order, index) in foodsOrders" :key='index'>
				<view class="bg-white order-border">
					<view class="section">
						<list-cell :hover="false" padding="50rpx 30rpx">
							<view class="w-100 d-flex flex-column">
								<view class="w-100 d-flex flex-column position-relative mt-30" style="margin-bottom: -40rpx;">
									<view class="w-100 d-flex align-items-center mb-40" v-for="(good, index) in order.orderGoods" :key="index">
										<view class="d-flex flex-column w-60 overflow-hidden">
											<view class="font-size-lg text-color-base mb-10 text-truncate">{{ good.goods.name }}</view>
										</view>
										<view class="d-flex w-40 align-items-center justify-content-between pl-30">
											<view class="font-size-base text-color-base">x{{ good.num }}</view>
											<view class="font-size-base text-color-base font-weight-bold">￥{{ good.price }}</view>
										</view>
									</view>
								</view>
							</view>
						</list-cell>
					</view>
					<view class="section">
						<list-cell :hover="false" padding="50rpx 30rpx">
							<view class="w-100 d-flex flex-column">
								<view class="pay-cell">
									<view>订单号</view>
									<view class="font-weight-bold">{{ order.order_no }}</view>
								</view>
								<view class="pay-cell">
									<view>支付状态</view>
									<view class="font-weight-bold">{{ order.status_text }}</view>
								</view>
								<view class="pay-cell">
									<view>支付方式</view>
									<view class="font-weight-bold">{{ order.pay_type == 1 ? '微信支付' : '余额支付' }}</view>
								</view>
								<view class="pay-cell">
									<view>订单金额</view>
									<view class="font-weight-bold">￥{{ order.total_price }}</view>
								</view>
								<view class="pay-cell">
									<view>实付金额</view>
									<view class="font-weight-bold">￥{{ order.total_price }}</view>
								</view>
							</view>
						</list-cell>
					</view>
					<view class="section">
						<list-cell :hover="false" padding="50rpx 30rpx">
							<view class="w-100 d-flex flex-column">
								<view class="pay-cell">
									<view>下单时间</view>
									<view class="font-weight-bold">{{ order.create_at }}</view>
								</view>
								<view class="pay-cell">
									<view>下单用户</view>
									<view class="font-weight-bold">{{ order.user_name }}</view>
								</view>
								<view class="pay-cell">
									<view>手机号码</view>
									<view class="font-weight-bold">{{ order.user_mobile }}</view>
								</view>
								<view class="pay-cell">
									<view>下单地址</view>
									<view class="font-weight-bold">{{ order.user_address }}</view>
								</view>
								<view class="pay-cell">
									<view>备注</view>
									<view class="font-weight-bold">{{ order.order_remark }}</view>
								</view>
							</view>
						</list-cell>
					</view>
					
					<!-- 按钮区域 -->
					<view class="button-section" v-if="order.status == 1">
						<view class="button-container">
						<!-- 	<button 
								class="cancel-btn" 
								@click="cancelOrder(order)"
							>
								取消订单
							</button> -->
							<button 
								class="continue-pay-btn" 
								@click="continuePay(order)"
							>
								继续支付
							</button>
						</view>
					</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	import listCell from '@/components/list-cell/list-cell'
	import {mapState, mapMutations, mapGetters} from 'vuex'
	// import ourLoading from '@/components/our-loading/our-loading.vue'
	
	export default {
		components: {
			listCell,
			// ourLoading
		},
		data() {
			return {
				foodsOrders: [],
				numForMading: 5,
				tabs: [
					{name: '全部', status: -1},
					{name: '待支付', status: 1}, 
					{name: '已完成', status: 2}
				],
				currentTab: 0
			}
		},
		computed: {
			...mapGetters(['isLogin'])
		},
		onPullDownRefresh() {
			this.takeFoods(this.tabs[this.currentTab].status);
		},
		onLoad() {
			
		},
		onShow() {
			this.takeFoods();
		},
		methods: {
			async takeFoods(status = -1) {
				if (!this.isLogin) {
					return;
				}
				let data = await this.$u.api.orderTakeFoods({status});
				uni.stopPullDownRefresh();
				if (data) {
					this.numForMading = data.concurrent;
					this.foodsOrders = data.list;
					console.log('订单数据:', this.foodsOrders); // 添加日志查看数据结构
				} else {
					this.foodsOrders = [];
				}
			},
			switchTab(index) {
				this.currentTab = index;
				this.takeFoods(this.tabs[index].status);
			},
			orders() {
				if(!this.$store.getters.isLogin) {
					uni.navigateTo({url: '/pages/components/pages/login/login'})
					return
				}
				uni.navigateTo({
					url: '/pages/components/pages/orders/orders'
				})
			},
			menu() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			makePhoneCall(shop) {
				uni.makePhoneCall({
					phoneNumber: shop.mobile,
					fail(res) {
						console.log(res)
					}
				})
			},
			// 取消订单
			cancelOrder(order) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该订单吗？',
					success: async (res) => {
						if (res.confirm) {
							let data = await this.$u.api.cancelOrder({order_no: order.order_no});
							if (data) {
								uni.showToast({
									title: '订单取消成功',
									icon: 'success'
								});
								this.takeFoods();
							}
						}
					}
				});
			},
                        // 继续支付
                        async continuePay(order) {
                                uni.showModal({
                                        title: '提示',
                                        content: '确定要继续支付该订单吗？',
                                        success: async (res) => {
                                                if (res.confirm) {
                                                        // 显示加载框
                                                        uni.showLoading({
                                                                title: '支付中...',
                                                                mask: true
                                                        });
                                                        
                                                        try {
                                                                let data = await this.$u.api.payUnify({
                                                                        order_no: order.order_no,
                                                                        pay_type: order.pay_type,
                                                                        address_id: order.user_address,
                                                                        order_remark: order.order_remark,
                                                                        name: order.user_name,
                                                                        tel: order.user_mobile,
                                                                });
                                                                
                                                                if (data) {
                                                                        if (order.pay_type == 1) {
                                                                                await this.weixinPay(data);
                                                                        } else {
                                                                                uni.hideLoading();
                                                                                uni.showToast({
                                                                                        title: '余额支付成功',
                                                                                        icon: 'success'
                                                                                });
                                                                                this.takeFoods(this.tabs[this.currentTab].status);
                                                                        }
                                                                }
                                                        } catch (error) {
                                                                console.error('支付失败:', error);
                                                                uni.hideLoading();
                                                                uni.showToast({
                                                                        title: '支付失败11，请重试',
                                                                        icon: 'none'
                                                                });
                                                        }
                                                }
                                        }
                                });
                        },
                        
                        async weixinPay(payData) {	
                                try {
                                        await new Promise((resolve, reject) => {
                                                uni.requestPayment({
                                                        provider: 'wxpay',
                                                        timeStamp: payData.timeStamp,
                                                        nonceStr: payData.nonceStr,
                                                        package: payData.package,
                                                        signType: 'MD5',
                                                        paySign: payData.paySign,
                                                        success: async (res) => {
                                                                uni.hideLoading();
                                                                await this.confirmPaymentStatus(orderNo);
                                                                resolve(res);
                                                        },
                                                        fail: (err) => {
                                                                uni.hideLoading();
                                                                if (err.errMsg.includes('cancel')) {
                                                                        uni.showToast({
                                                                                title: '支付已取消',
                                                                                icon: 'none'
                                                                        });
                                                                } else {
                                                                        uni.showToast({
                                                                                title: '支付失败，请重试',
                                                                                icon: 'none'
                                                                        });
                                                                }
                                                                reject(err);
                                                        }
                                                });
                                        });

                                } catch (error) {
                                        console.error('微信支付失败:', error);
                                        uni.hideLoading();
                                        uni.showToast({
                                                title: '支付失败，请重试',
                                                icon: 'none'
                                        });
                                }
                        },
                        
                        async confirmPaymentStatus(orderNo) {
                                try {
                                        await new Promise(resolve => setTimeout(resolve, 2000));
                                        
                                        let retryCount = 0;
                                        const maxRetries = 5;
                                        
                                        while (retryCount < maxRetries) {
                                                const orderDetail = await this.$u.api.getOrderDetail({ order_no: orderNo });
                                                if (orderDetail && orderDetail[0]) {
                                                        if (orderDetail[0].status === 2) { 
                                                                uni.showToast({
                                                                        title: '支付成功',
                                                                        icon: 'success'
                                                                });
                                                                this.takeFoods(this.tabs[this.currentTab].status);
                                                                return true;
                                                        } else if (orderDetail[0].status === 1) { 
                                                                retryCount++;
                                                                await new Promise(resolve => setTimeout(resolve, 1000));
                                                                continue;
                                                        }
                                                }
                                                retryCount++;
                                                await new Promise(resolve => setTimeout(resolve, 1000));
                                        }
                                        
                                        uni.showToast({
                                                title: '支付处理中，请稍后查看订单状态',
                                                icon: 'none'
                                        });
                                        this.takeFoods(this.tabs[this.currentTab].status);
                                        
                                } catch (error) {
                                        console.error('确认支付状态失败:', error);
                                        uni.showToast({
                                                title: '支付状态确认失败，请手动刷新',
                                                icon: 'none'
                                        });
                                        this.takeFoods(this.tabs[this.currentTab].status);
                                }
                        }
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-top: 100rpx;
	}

	.tabs {
		display: flex;
		background: #fff;
		padding: 20rpx 0;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 9999999;
		
		.tab-item {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			font-size: 28rpx;
			color: #666;
			
			&.active {
				color: #289365;
				font-weight: bold;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 80rpx;
					height: 4rpx;
					background: #289365;
					border-radius: 2rpx;
				}
			}
		}
	}
	
	/* #ifdef H5 */
	page {
		min-height: 100%;
		background-color: #c2e9f5;
		// background-color: $bg-color;
	}
	/* #endif */
	
	.order-box {
		padding: 20rpx;
		/* #ifdef H5 */
		margin-bottom: 100rpx;
		/* #endif */
	}
	
	.order-border {
		border-radius: 8rpx; 
	}
	
	.drinks-img {
		width: 260rpx;
		height: 260rpx;
	}
	
	.tips {
		margin: 60rpx 0 80rpx;
		line-height: 48rpx;
	}
	
	.drink-btn {
		width: 320rpx;
		border-radius: 50rem !important;
		margin-bottom: 40rpx;
		font-size: $font-size-base;
		line-height: 3.0;
	}
	
	@mixin arch {
		content: "";
		position: absolute;
		background-color: $bg-color;
		width: 30rpx;
		height: 30rpx;
		bottom: -15rpx;
		z-index: 10;
		border-radius: 100%;
	}
	
	.section {
		position: relative;
		
		&::before {
			@include arch;
			left: -15rpx;
		}
		
		&::after {
			@include arch;
			right: -15rpx;
		}
	}
	
	.pay-cell {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: $font-size-base;
		color: $text-color-base;
		margin-bottom: 40rpx;

		&:nth-last-child(1) {
			margin-bottom: 0;
		}
	}
	
	.sort-num {
		font-size: 64rpx;
		font-weight: bold;
		color: $text-color-base;
		line-height: 2;
	}
	
	.steps__img-column {
		display: flex;
		margin: 30rpx 0;
		
		.steps__img-column-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			
			image {
				width: 80rpx;
				height: 80rpx;
			}
			.unactive {
				color: #919293;
			}
		}
	}
	
	.steps__text-column {
		display: flex;
		margin-bottom: 40rpx;
		
		.steps__text-column-item {
			flex: 1;
			display: inline-flex;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: $font-size-base;
			color: $text-color-assist;
			
			&.active {
				color: $text-color-base;
				font-weight: bold;
				
				.steps__column-item-line {
					background-color: $text-color-base;
				}
			}
			
			.steps__column-item-line{
				flex: 1;
				height: 2rpx;
				background-color: #919293;
				transform: scaleY(0.5);
			}
			
			.steps__text-column-item-text {
				margin: 0 8px;
			}
		}
	}
	.icon-lamp, .icon-daojishi, .icon-takeout, .icon-doorbell{
		font-size: 60rpx;
	}
	.iconfont-unidrink {
		color: #289365;
	}
	
	/* 按钮区域样式 */
	.button-section {
		padding: 30rpx;
		background: #fff;
		border-top: 1rpx solid #f5f5f5;
	}
	
	.button-container {
		display: flex;
		justify-content: flex-end;
		
		.cancel-btn {
			margin-right: 20rpx;
		}
	}
	
	.cancel-btn {
		background: #ff4d4f;
		color: #fff;
		border: none;
		border-radius: 50rpx;
		padding: 0 40rpx;
		height: 70rpx;
		font-size: 28rpx;
		line-height: 70rpx;
		
		&:active {
			background: #d9363e;
		}
	}
	
	.continue-pay-btn {
		background: #1A9364;
		color: #fff;
		border: none;
		border-radius: 50rpx;
		padding: 0 40rpx;
		height: 70rpx;
		font-size: 28rpx;
		line-height: 70rpx;
		
		&:active {
			background: #1A9364;
		}
	}
</style>
